package com.zlz.mail;

import com.rabbitmq.client.Channel;
import com.zlz.server.constant.MailConstant;
import com.zlz.server.pojo.Employee;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;


/**
 * @author: zlz
 * @date: 2021/3/14 23:40
 * @description:
 * @since: JDK1.8
 */
@Component
@Slf4j
public class MailReceiver {
    private static final String MAIL_LOG = "mail_log";
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private MailProperties mailProperties;
    @Resource
    private TemplateEngine templateEngine;

    @Resource
    private RedisTemplate redisTemplate;

    @RabbitListener(queues = MailConstant.MAIL_QUEUE_NAME)
    public void handler(Message message, Channel channel) {
        Employee employee = (Employee)message.getPayload();
        MessageHeaders messageHeaders = message.getHeaders();
        // 消息序号
        long tag = (long)messageHeaders.get(AmqpHeaders.DELIVERY_TAG);
        String msgId = (String)messageHeaders.get("spring_returned_message_correlation");
        HashOperations hashOperations = redisTemplate.opsForHash();
        try {
            if (hashOperations.entries(MAIL_LOG).containsKey(msgId)) {
                log.error("消息{}已被消费", msgId);
                channel.basicAck(tag, false);
                return;
            }
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(employee.getEmail());
            helper.setSubject("入职欢迎邮件");
            Context context = new Context();
            context.setVariable("name", employee.getName());
            context.setVariable("posName", employee.getPosition().getName());
            context.setVariable("joblevelName", employee.getJoblevel().getName());
            context.setVariable("departmentName", employee.getDepartment().getName());
            String mail = templateEngine.process("mail", context);
            helper.setText(mail, true);
            javaMailSender.send(mimeMessage);
            log.info("邮件发送成功");
            // 将消息id存入redis
            hashOperations.put(MAIL_LOG, msgId, "ok");
            channel.basicAck(tag, false);
        } catch (Exception e) {
            /**
             * 手动确认消息
             * tag: 消息id
             * multiple: 是否确认多条
             * requeue: 消息是否重回队列
             */
            try {
                channel.basicNack(tag, false, true);
            } catch (IOException ioException) {
                log.error("邮件发送失败, {}", e.getMessage());
            }
            log.error("邮件发送失败, {}", e.getMessage());
        }


    }
}
